package com.yjd.api.user;

import com.yjd.comm.bank.model.AuthBankModel;
import com.yjd.comm.bank.model.BankCardDataModel;
import com.yjd.comm.bank.model.BankInfoModel;
import com.yjd.comm.bank.model.BankModel;
import com.yjd.comm.bank.service.IBankInfoService;
import com.yjd.comm.bank.service.IBankService;
import com.yjd.comm.base.control.MobileBaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.enums.ReferenceTypeEnum;
import com.yjd.comm.system.model.SysParamModel;
import com.yjd.comm.system.util.SysParamUtil;
import com.yjd.comm.user.dto.UserSession;
import com.yjd.comm.user.util.UserUtil;
import com.yjd.comm.util.AuthBankUtils;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.vo.Constant;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by yjd-wap on 2017/6/28.
 */

@Controller
@Scope("prototype")
@RequestMapping("/bank")
public class BankControl extends MobileBaseControl {
    @Resource
    private IBankInfoService bankInfoService;

    @Resource
    private IBankService bankService;

    /**
     * 返回用户当前绑定的银行卡信息
     * []
     *
     * @param
     * @return void
     * @throws
     */
    @RequestMapping(value = "/card", method = RequestMethod.POST)
    public void currentBankCard() throws Exception {
        UserSession user = this.getUserSession();
        if (null == user) {
            FrameUtil.throwBaseException1("请先登陆");
        }

        BankModel userBankCard = bankService.getModelOne(FrameUtil.newHashMap("user_id", user.getUser_id()), DbWREnums.READ);
        if (null == userBankCard) {
            FrameUtil.throwBaseException1("请先绑定银行卡");
        }

        BankInfoModel bankBasicInfo = bankInfoService.getModelById(userBankCard.getBank_id(), DbWREnums.READ);

        // 构造返回信息
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        paramMap.put("userBankCardInfo", userBankCard);
        paramMap.put("bankBasicInfo", bankBasicInfo);
        this.successData(paramMap);
    }

    /**
     * 更新用户的银行卡信息
     *
     * @return void
     * @throws
     */
    @RequestMapping("/update")
    public void updateBankcard(String idName, String idNumber, String bankCardNo, String reserveMobileNo) throws Exception {
        UserSession userSession = this.getUserSession();
        if (null == userSession) {
            FrameUtil.throwBaseException1("请先登陆");
        }

        // 参数验证
        if (StringUtils.isEmpty(idName) ||
                StringUtils.isEmpty(idNumber) ||
                StringUtils.isEmpty(bankCardNo) ||
                StringUtils.isEmpty(reserveMobileNo)) {
            FrameUtil.throwBaseException1("参数错误");
        }

        // TODO 四要素认证

        // TODO 更新银行卡信息（暂不做）

        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        this.successData(paramMap);
    }

    /**
     * 绑定银行卡
     *
     * @param bankcode 银行卡号
     * @param mobile   预留手机号
     * @param idname   身份证姓名
     * @param idcard   身份证号码
     * @return void
     * @throws
     */
    @RequestMapping(value = "/binding", method = RequestMethod.POST)
    public void bindingBankCard(@RequestParam String bankcode, @RequestParam String mobile, @RequestParam String idname, @RequestParam String idcard) throws Exception {

        if (StringUtils.isBlank(idname)) {
            super.errorMsg("请输入真实姓名!");
            return;
        }

        if (StringUtils.isBlank(idcard)) {
            super.errorMsg("请输入身份证号!");
            return;
        }

        if (StringUtils.isBlank(bankcode)) {
            super.errorMsg("请输入银行卡号!");
            return;
        }

        if (StringUtils.isBlank(mobile)) {
            super.errorMsg("请输入手机号码!");
            return;
        }

        if (!NumberUtils.isNumber(mobile)) {
            super.errorMsg("请输入正确的手机号哟!");
            return;
        }

        SysParamModel sysParamModel = SysParamUtil
                .getSysParamModel(Constant.SysParamKeyEnum.REGISTER_REGEX);
        Matcher regex = Pattern.compile(sysParamModel.getParam_value())
                .matcher(mobile.toString());
        if (!regex.matches()) {
            this.errorMsg(null, "请输入正确的手机号码!");
            return;
        }

        bankcode = bankcode.trim();
        UserSession userSession = super.getUserSession();

        BankModel bankCardModel = bankService.getModelById(userSession.getUser_id(), DbWREnums.READ);
        if (bankCardModel != null) {
            FrameUtil.throwBaseException1("您已经绑过银行卡");
        }

        bankCardModel = bankService.getModelOne(FrameUtil.newHashMap("id_number", idcard.trim()), DbWREnums.READ);
        if (bankCardModel != null) {
            FrameUtil.throwBaseException1("该身份证已经绑定过银行卡");
        }

        try {
            // 调用接口验证通过 更新银行卡信息
            AuthBankModel authModel = new AuthBankModel();
            authModel.setUser_id(userSession.getUser_id());
            authModel.setBank_card_no(bankcode);
            authModel.setBank_card_idname(idname);
            authModel.setBank_card_idcard(idcard);
            authModel.setBank_card_mobile(mobile);
            authModel.setApp_type(AuthBankUtils.FOUR);
            authModel.setReqeust_client("mfq");
            BankCardDataModel bandCard = AuthBankUtils.authBank(authModel);

            Long bank_id = 0L;
            BankInfoModel bankInfo = null;
            if (bandCard != null && !org.apache.commons.lang.StringUtils.isBlank(bandCard.getBankCode())) {
                Map<Object, Object> bankParam = new HashMap<Object, Object>();
                bankParam.put("bank_code", bandCard.getBankCode());
                bankInfo = bankInfoService.getModelOne(bankParam, DbWREnums.WRITE);
                if (bankInfo != null) {
                    bank_id = bankInfo.getBank_id();
                } else {
                    this.errorMsg(null, "您认证的银行卡所属银行不存在，请核实后提交或联系客服！");
                    return;
                }
            }

            Long currtime = FrameUtil.getTime(null);
            BankModel bankModel = new BankModel();
            bankModel.setUser_id(userSession.getUser_id());
            bankModel.setId_name(idname);
            bankModel.setId_number(idcard);
            bankModel.setBank_id(bank_id);
            bankModel.setBank_card_number(bankcode);
            bankModel.setCreate_time(currtime);
            bankModel.setBank_mobile(Long.parseLong(mobile));
            bankModel.setLast_update_time(currtime);
            bankService.bindingBank(bankModel);

            String limit = SysParamUtil.getValue(Constant.SysParamKeyEnum.CREDIT_LIMIT_MIN);
            this.successData("绑定银行卡成功", FrameUtil.newHashMap(
                    "credit_limit", limit,
                    "idname",UserUtil.disposeIdCard(idname),
                    "idcard",UserUtil.disposeIdCard(idcard),
                    "bank_name", bankInfo.getBank_name(),
                    "bank_code", UserUtil.disposeBankCardNo(bankcode),
                    "bank_img", ServletUtil.getFileUrl(ReferenceTypeEnum.BANK_PICTURE.getPath() + bankInfo.getBank_code() + ".png"),
                    "bank_mobile", UserUtil.disposeMobile(mobile)
            ));
        } catch (Exception e) {
            logger.info("pc端实名认证银行卡失败，修改认证记录状态为失败" + userSession.getUser_id() + " " + bankcode + " " + idcard + " " + idcard + " " + mobile);
            throw e;
        }
    }
}
